<template>
    <el-dialog
      :title="helpTextTitle"
      :fullscreen="dialogFullscree"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="80%"
      class="showDialogClass"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="90px"
      >
        <el-form-item label="资料标题:">
          <el-input v-model="form.textTitle" />
        </el-form-item>
        <el-col
          :span="12"
          style="max-width: 37%"
        >
          <el-form-item label="资料类别:">
            <el-select
              v-model="form.textType"
              placeholder="请选择"
              clearable
              size="small"
            >
              <el-option
                v-for="item in textTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          style="max-width:21%"
        >
          <el-form-item label="排序:">
            <el-input
              v-model="form.sort"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片:">
            <el-col
              :span="8"
              width="40%"
            >
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :limit="999"
                :on-success="handleAvatarSuccess"
              >
                <img
                  v-if="imageUrl"
                  :src="imageUrl"
                  class="avatar"
                >
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                />
              </el-upload>
            </el-col>
            <el-form-item label="缩略图:">
              <el-col
                :span="12"
                width="30%"
              >
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :disabled="true"
                >
                  <img
                    v-if="videoThumbnail"
                    :src="videoThumbnail"
                    class="avatar"
                  >
                  <i
                    v-else
                    class="el-icon-plus avatar-uploader-icon"
                  />
                </el-upload>
              </el-col>
            </el-form-item>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="视频:">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :before-upload="onBeforeUploadVideo"
            :on-success="onVideoSuccess"
            :multiple="fileMultiple"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileData"
          >
            <el-button
              size="small"
              type="primary"
            >
              点击上传
            </el-button>
          </el-upload>
        </el-form-item>
        </el-col>
       <el-col :span="24">
        <el-form-item label="资料内容:">
          <quill-editor
            v-model="textContent"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
          />
        </el-form-item>
       </el-col>
       <el-col
          :span="12"
          style="max-width: 80%"
        >
          <el-form-item label="标签:">
            <el-tag
              v-model="form.textLabel"
              v-for="(item, index) in items"
              size="mini"
              @click="changeColor(index)"
              :key="item.id"
              :effect="item.tagEffect"
              :checked="item.tagEffect=='dark'"
            >
              {{ item.label }}
            </el-tag>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          style="max-width: 40%"
        >
          <el-form-item label="置顶时间:">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              style="max-width: 70%"
              value-format="yyyy-MM-dd"
              v-model="form.textIsTopDate"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          style="max-width: 80%"
        >
          <el-form-item label="是否置顶:">
            <el-radio-group v-model="form.textIsTop">
              <el-radio :label="1">
                置顶
              </el-radio>
              <el-radio :label="0">
                不置顶
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          style="max-width: 40%"
        >
          <el-form-item label="是否热点:">
            <el-radio-group v-model="form.textIsHot">
              <el-radio :label="1">
                热点
              </el-radio>
              <el-radio :label="0">
                非热点
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          style="max-width: 80%"
        >
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.description"
            />
          </el-form-item>
        </el-col>
      </el-form>
      <!-- 底部 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="onSubmit"
        > 确定 </el-button>
        <el-button @click="handleClose"> 取消 </el-button>
      </span>
  
      <!-- 图片弹框 -->
      <el-dialog
        title="图片"
        :visible.sync="dialogVisibleImg"
        :close-on-click-modal="false"
        width="20%"
        append-to-body
      >
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="true"
          :on-success="coverUploadSuccess"
          :before-upload="coverUploadProgress"
          ref="upload"
          :limit="999"
          :file-list="fileList"
          list-type="picture-card"
        >
          <i
            slot="default"
            class="el-icon-plus"
          />
          <div
            slot="file"
            slot-scope="{file}"
          >
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            >
          </div>
        </el-upload>
  
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="handleCloseImg"
          > 确定 </el-button>
          <el-button @click="dialogVisibleImg = false"> 取消 </el-button>
        </span>
      </el-dialog>
      <!-- 视频弹框 -->
      <el-dialog
        title="视频"
        :visible.sync="dialogVisibleVideo"
        :close-on-click-modal="false"
        width="22%"
        append-to-body
      >
        <el-upload
          class="upload-demo"
          drag
          :action="uploadUrl"
          accept="video/*"
          :before-upload="onBeforeUploadVideo"
          :on-success="onSuccessVideo"
          :on-error="onErrorVideo"
          :multiple="false"
          :limit="999"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <div
            class="el-upload__tip"
            slot="tip"
          >
            只能上传mp4文件,且不超过500kb
          </div>
        </el-upload>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="handleCloseVideo"
          > 确定 </el-button>
          <el-button @click="dialogVisibleVideo = false"> 取消 </el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </template>
  
  <script>
    import { quillEditor } from "vue-quill-editor";
    import "quill/dist/quill.core.css";
    import "quill/dist/quill.snow.css";
    import "quill/dist/quill.bubble.css";
    import webapp from "@/config/webapp";
    import {
      helpTextDetail,
      helpTextSave,
      videoCapture,
    } from "@/api/datacentersg/archives/helpText";
    import { getList } from "@/api/datacentersg/archives/label";
    import store from "@/store";
  
    class Photo {
      constructor (name, url) {
        this.name = name;
        this.url = url;
      }
    }
  
    // 富文本的工具栏
    const toolbarOptions=[
      [`bold`, `italic`, `underline`, `strike`], // 加粗 斜体 下划线 删除线
      [`blockquote`, `code-block`], // 引用  代码块
      [{ header: 1 }, { header: 2 }], // 1、2 级标题
      [{ list: `ordered` }, { list: `bullet` }], // 有序、无序列表
      [{ script: `sub` }, { script: `super` }], // 上标/下标
      [{ indent: `-1` }, { indent: `+1` }], // 缩进
      [{ direction: `rtl` }], // 文本方向
      [{ size: [`12`, `14`, `16`, `18`, `20`, `22`, `24`, `28`, `32`, `36`] }], // 字体大小
      [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
      [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
      // [{ font: ['songti'] }], // 字体种类
      [{ align: [] }], // 对齐方式
      [`clean`], // 清除文本格式
      [`image`, `video`], // 链接、图片、视频
    ]
  
    export default {
      name: `addEditor`,
      components: { quillEditor },
      data () {
        const _self = this;
        return {
          helpTextTitle: ``, //标题
          dialogFullscree: false, //是否全屏展示dialog
          dialogVisible: false,
          readOnly: false,
          fileMultiple: false,
          fileData: [],
          radio: `0`,
          // 富文本编辑器配置
          editorOption: {
            modules: {
              toolbar: {
                container: toolbarOptions, // 工具栏
                handlers: {
                  'video': () => {
                    // 覆盖默认的上传视频，点击视频图标，显示弹窗
                    _self.dialogVisibleVideo = true;
                  },
                  "image": () => {
                    // 覆盖默认的上传视频，点击视频图标，显示弹窗
                    _self.dialogVisibleImg = true;
                  },
                },
              },
            },
            placeholder: `请输入正文`,
          },
          fileList: [],
          imageUrls: [],
          videoUrls: [],
          videoSuccess: ``,
          uploadUrl: webapp.uploadUrl,
          dialogVisibleLue: false,
          imageUrl: ``, //图片
          disabled: false,
          dialogVisibleImg: false,
          dialogVisibleVideo: false,
          form: {
            textTitle: ``, //资料标题
            textType: ``, //资料类别
            textIsTopDate: ``, //置顶时间
            textIsTop: ``, //是否置顶
            textIsHot: ``, //是否热点
            textLabel: ``, //标签
            description: ``, //备注
            sort: ``, //排序
            searchkeys: [],
          },
          textContent: ``,
          textHelpId: ``,
          textTypeList: [
            {
              name: `帮助文档`,
              value: 0,
            },
            {
              name: `常见问题`,
              value: 1,
            },
          ],
          tagType: ``,
          items: [],
          videoThumbnail: null,
        };
      },
      methods: {
        initdata () {
          this.items.map(item => {
            item.tagEffect = `plain`;
            return item;
          })
          this.form = JSON.parse(JSON.stringify({
            textTitle: ``, //资料标题
            textType: ``, //资料类别
            textIsTopDate: ``, //置顶时间
            textIsTop: ``, //是否置顶
            textIsHot: ``, //是否热点
            textLabel: ``, //标签
            description: ``, //备注
            sort: ``, //排序
            searchkeys: [],
          }));
        },
        init (id, flag) {
          this.dialogVisible = true;
          this.readOnly = flag == `look`;
          //如果有传入id 就表示当前为修改操作，没有传入就是新增操作
          this.radio = `0`;
  
          if (id != null) {
            this.getHelpTextDetail(id);
            this.helpTextTitle = `编辑`;
          }
          else {
            this.helpTextTitle = `新增`;
            this.dialogVisible = true;
          }
        },
        getHelpTextDetail (id) {
          // this.initdata();
          this.getTagDataList();
          const params = {
            userId: store.getters.userId.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            data: { textId: id },
          };
          helpTextDetail(params).then((data) => {
            if (data.result) {
              this.textHelpId = data.resultdata.data.textId;
              this.form.textTitle = data.resultdata.data.textTitle;
              this.textContent = data.resultdata.data.textContent;
              this.form.textType = data.resultdata.data.textType;
              this.form.textIsTopDate = data.resultdata.data.textIsTopDate;
              this.form.textIsTop = data.resultdata.data.textIsTop;
              this.form.textIsHot = data.resultdata.data.textIsHot;
              this.form.searchkeys = data.resultdata.data.textLabel;
              this.form.description = data.resultdata.data.description;
              this.form.sort = data.resultdata.data.textOrder;
              this.imageUrl = data.resultdata.data.textImage//资料图片
              this.videoThumbnail = data.resultdata.data.textThumbnail//资料缩略图
              this.videoSuccess = data.resultdata.data.textVideo;//视频
              const photoList = [];
              photoList.push(new Photo(this.videoSuccess));
              this.fileData = photoList;
  
              let arr = [];
              setTimeout(() => {
                if (this.form.searchkeys) {
                  arr = this.form.searchkeys.split(`,`);
                  this.form.searchkeys  = arr;
                  for (let j = 0; j < this.items.length; j++) {
                    this.items[j].tagEffect = `plain`;
                  }
                  for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < this.items.length; j++) {
                      if (arr[i] == this.items[j].label) {
                        this.items[j].tagEffect = `dark`;
                      }
                    }
                  }
                }
              }, 100);
              this.form.dialogVisible = true;
              this.$forceUpdate();
            }
          });
        },
        getTagDataList () {
          const params = {
            data: { fileBusinessTypeId: `111` },
            userId: store.getters.userId.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
          };
          getList(params).then((data) => {
            if (data.result) {
              const items = [];
              data.resultdata.data.forEach(function (obj, index) {
                items.push({
                  label: obj.labelName,
                  index: index,
                  tagEffect: `plain`,
                });
              });
              this.items = items;
            }
          });
        },
        onSubmit () {
          if (this.form.textTitle == `` || this.form.textTitle == null) {
            this.$message({
              message: `请输入资料标题！`,
              type: `error`,
            });
            return false;
          }
          if (this.textContent == `` || this.textContent == null) {
            this.$message({
              message: `请输入资料内容！`,
              type: `error`,
            });
            return false;
          }
          if (this.form.sort == `` || this.form.sort == null) {
            this.$message({
              message: `请输入资料排序！`,
              type: `error`,
            });
            return false;
          }
          const params = {
            userId: store.getters.userId.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
            data: {
              textBussinessTypeCode: `111`,
              textTitle: this.form.textTitle,
              textContent: this.textContent,
              description: this.form.description,
              textIsTopDate: this.form.textIsTopDate,
              textType: this.form.textType,
              textIsTop: this.form.textIsTop,
              textIsHot: this.form.textIsHot,
              textLabel: this.form.searchkeys.toString(),
              textOrder: this.form.sort,
              textThumbnail: this.videoThumbnail,
              textImage: this.imageUrl,
              textVideo: this.videoSuccess,
            },
          };
          if (this.helpTextTitle === `新增`) {
            helpTextSave(params).then((data) => {
              if (data.result === true) {
                this.$message({
                  type: `success`,
                  message: `操作成功`,
                });
                this.cancel();
                this.$emit(`refresh`);
              }
              else {
                this.$message({
                  type: `warning`,
                  message: data.message,
                });
              }
            });
          }
          else if (this.helpTextTitle === `编辑`) {
            const params = {
              userId: store.getters.userId.toString(),
              token: store.getters.token.toString(),
              userName: store.getters.userName.toString(),
              data: {
                textId: this.textHelpId,
                textTitle: this.form.textTitle,
                textContent: this.textContent,
                description: this.form.description,
                textIsTopDate: this.form.textIsTopDate,
                textType: this.form.textType,
                textIsTop: this.form.textIsTop,
                textIsHot: this.form.textIsHot,
                textLabel: this.form.searchkeys.toString(),
                textOrder: this.form.sort,
                textThumbnail: this.videoThumbnail,
                textImage: this.imageUrl,
                textVideo: this.videoSuccess,
              },
            };
            helpTextSave(params).then((data) => {
              if (data.result === true) {
                this.$message({
                  type: `success`,
                  message: `操作成功`,
                });
                this.cancel();
                this.$emit(`refresh`);
              }
              else {
                this.$message({
                  type: `warning`,
                  message: data.message,
                });
              }
            });
          }
        },
        async changeColor (id) {
          const baginState = this.items[id].tagEffect == `plain`;
          this.items[id].tagEffect =
            this.items[id].tagEffect == `plain` ? `dark` : `plain`;
          for (let i = 0; i < this.items.length; i++) {
            if (this.items[i].tagEffect == `dark`) {
              this.form.searchkeys.push(this.items[i].label);
            }
          }
        },
        onEditorBlur (quill) {
          // 失去焦点事件
          console.log(`editor blur!`, quill)
        },
        onEditorFocus (quill) {
          // 获得焦点事件
          console.log(`editor focus!`, quill)
        },
        onEditorReady (quill) {
          // 准备富文本编辑器
          console.log(`editor ready!`, quill)
        },
        onEditorChange ({ quill, html, text }) {
          // 内容改变事件
          this.textContent = html;
        },
        onVideoSuccess (file) {
          console.log(file.url, `视频`)
          this.videoSuccess = file.url
          const params={
            data: { path: file.url },
            userId: store.getters.userId.toString(),
            token: store.getters.token.toString(),
            userName: store.getters.userName.toString(),
          }
          videoCapture(params).then((data) => {
            this.videoThumbnail = data.resultdata
          })
  
        },
        handleRemove (file, fileList) {
          console.log(file, fileList);
        },
        handlePreview (file) {
          console.log(file);
        },
        handleExceed (files, fileList) {
          this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove (file, fileList) {
          return this.$confirm(`确定移除 ${ file.name }？`);
        },
        handleAvatarSuccess (res, file) {
          this.imageUrl = file.response.url;
        },
        coverUploadSuccess (file, fileList) {
            const url = file.url;
            // 插入图片到富文本编辑器
            const quill = this.$refs.myQuillEditor.quill;
            const index = quill.getSelection()?.index;//获取光标所在位置
            quill.insertEmbed(index, `image`, `${url}`);//插入图片，dt.url为服务器返回的图片地址
            quill.setSelection(index + 1)
            // 将图片URL保存到数组中
            this.imageUrls.push(url);
            this.fileList = [];
            console.log(this.imageUrls,"imageUrls")
        },
        coverUploadProgress (res, file) {
            console.log(res, file, `res`);
        },
        handleCloseImg () {
          this.fileList = [];
            this.dialogVisibleImg = false;
        },
        handleRemoveImg(file) {
          const fileList = this.$refs.upload.fileList;
          const index = fileList.indexOf(file);
          fileList.splice(index, 1);
        },
        onBeforeUploadVideo (file) {
          const testmsg = file.name.substring(file.name.lastIndexOf(`.`) + 1);
          const extension = testmsg === `mp4`;
          if (!extension) {
            this.$message({
              message: `上传文件只能是.mp4格式!`,
              type: `warning`,
            });
          }
          return extension;
        },
        onSuccessVideo (res) {
          const url = res.url;
            // 插入图片到富文本编辑器
            const quill = this.$refs.myQuillEditor.quill;
            const index = quill.getSelection()?.index;//获取光标所在位置
            quill.insertEmbed(index, `video`, `${url}`);//插入图片，dt.url为服务器返回的图片地址
            quill.setSelection(index + 1)
            // 将图片URL保存到数组中
            this.videoUrls.push(url);
        },
        onErrorVideo () {
          this.$message.error(`上传失败`)
        },
        handleCloseVideo () {
          this.dialogVisibleVideo = false;
        },
        cancel () {
          this.dialogVisible = false;
          this.form = {
            textTitle: ``, //资料标题
            textType: ``, //资料类别
            textIsTopDate: ``, //置顶时间
            textIsTop: ``, //是否置顶
            textIsHot: ``, //是否热点
            textLabel: ``, //标签
            description: ``, //备注
            sort: ``,
            searchkeys: [],
          };
          this.fileData = [];
          this.textContent = ``;
          this.imageUrl="";
          this.videoThumbnail="";
          this.videoSuccess="";
        },
        handleClose () {
          this.cancel();
        },
      },
    };
  </script>
  
  <style scoped>
  /* >>>.el-select > .el-input{
      width: 300px;
  } */
  >>> .el-form-item__label {
    font-size: 14px;
    font-weight: 700;
    color: #000;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  >>> .ql-editor {
    min-height: 150px;
  }
  /* >>>.el-upload{
    border: 1px dashed #aaa;
  } */
  >>>.avatar-uploader .el-upload {
      border: 1px dashed #a9a9a9 !important;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 150px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }
    .avatar {
      width: 150px;
      height: 150px;
      display: block;
    }
  </style>
  